<?php

App::uses('AppModel', 'Model');

class Campaign extends AppModel {
    
    public $belongsTo = array( 'Client' );
    
    public $hasAndBelongsToMany = array('Location');
    public $hasMany = array(
        'CampaignsLocation' => array(
            'dependent'=>true
        )
    );
    
    public $validate = array(
        'name' => array(
            'rule'    => 'notEmpty',
            'message' => 'Morate uneti naziv kampanje.'
        )
    );
    
    public function afterFind($results, $primary=false) {
        parent::afterFind($results, $primary);
        
        if (! empty($results)) {
            foreach($results as &$row) {
                if(empty($row['Campaign']) || !isset($row['Campaign']['name'])) {
                    continue;
                }
                
                if (empty($row['Client']) && !empty($row['Campaign']['client_id'])) {
                    $row['Client'] = Set::extract('Client', $this->Client->findById($row['Campaign']['client_id'], 'Client.*'));
                }
                
                // update Campaigns label
                $row['Campaign']['label'] = $row['Campaign']['name'] . " / " . 
                                            @$row['Client']['name'];
            }
        }
        
        return $results;
    }
    
    public function deleteRelatedData() {
        if ($this->id) {
            $this->CampaignsLocation->deleteAll(array('CampaignsLocation.campaign_id' => $this->id));
        }
    }

    public function getByDateAndLocation($date, $locationId) {
        $sql = "
            SELECT Campaign.id, CampaignsLocation.start, CampaignsLocation.end, Client.name
            FROM
                campaigns Campaign
                INNER JOIN campaigns_locations CampaignsLocation 
                    ON Campaign.id=CampaignsLocation.campaign_id
                INNER JOIN clients Client ON Client.id=Campaign.client_id
            WHERE
                CampaignsLocation.start <= '{$date}' AND
                CampaignsLocation.end   >= '{$date}' AND
                CampaignsLocation.location_id = {$locationId}
            LIMIT 1
        ";
        $data = $this->query($sql);
        if (! empty($data)) {
            $data = $data[0];
        }

        return $data;
    }

    public function locations($id = null) {
        if (! $id) {
            $id = $this->id;
        }
        $locations = $this->Location->find('all', array(
            'fields' => array('Location.*', 'CampaignsLocation.*'),
            'conditions' => array('CampaignsLocation.campaign_id' => $id),
            'recursive' => false,
            'joins' => array(
                array(
                    'table' => 'campaigns_locations',
                    'alias' => 'CampaignsLocation',
                    'type'  => 'INNER',
                    'conditions' => 'CampaignsLocation.location_id=Location.id'
                )
            )
        ));

        return $locations;
    }
    
}

?>